//Ymt base
(function (window, $m, undefined) {

	//$m
	$m = window[$m] = window['$m'] = {};

	var __deferred, isReady,
		mix = function (ori, ext, isrewrite) {
			if (!ext || !ori) return ori;
			isrewrite === undefined && (isrewrite = !0);
			for (var key in ext)
				if (isrewrite || !(key in ori)) ori[key] = ext[key];
			return ori
		};

	//dom ready
	function ready() {
		var doc = window.document;
		if (doc.readyState === "complete") {
			dt();
		}
		if (!doc.body) {
			return setTimeout(function () {
				ready()
			}, 1);
		}

		function dt() {
			__deferred.resolve();
			isReady = !0;
		}

		function doScrollCheck() {
			try {
				doc.documentElement.doScroll("left");
			} catch (e) {
				setTimeout(doScrollCheck, 1);
				return;
			}
			dt();
		}
		var domLoaded;
		if (doc.addEventListener) {
			domLoaded = function () {
				doc.removeEventListener("DOMContentLoaded", domLoaded, false);
				dt();
			};
			doc.addEventListener("DOMContentLoaded", domLoaded, false);
		} else if (doc.attachEvent) {
			domLoaded = function () {
				if (doc.readyState === "complete") {
					doc.detachEvent("onreadystatechange", domLoaded);
					dt();
				}
			};
			doc.attachEvent("onreadystatechange", domLoaded);
			var toplevel = false;
			try {
				toplevel = window.frameElement == null;
			} catch (e) {}
			if (doc.documentElement.doScroll && toplevel) {
				doScrollCheck();
			}
		}
	}


	mix($m, {
		version: "3.0",
		mix: mix,

		//log
		log: function (content, method) {
			if (!$m.isUndefined(window.console) && console.log) console[method && console[method] ? method : "log"](content)
		},

		//object prototype 继承
		extend: function (ori, ext) {
			if (!ext || !ori) return ori;
			var d = ext.prototype,
				j = function (d) {
					function b() {}
					b.prototype = d;
					return new b
				}(d);
			ori.prototype = j;
			j.constructor = ori;
			ori.superclass = d;
			return ori
		},

		//对origin类的原型进行扩展
		augment: function () {
			var args = arguments,
				lastIndex = args.length - 1,
				origin = args[0],
				last = args[lastIndex];

			$m.isBoolean(last) || (last = undefined, lastIndex++);
			for (j = 1; j < lastIndex; j++) mix(origin.prototype, args[j].prototype || args[j], last);
			return origin;
		},

		//合并所有参数对象
		merge: function () {
			var a = {},
				b, length = arguments.length;
			for (b = 0; b < length; ++b) mix(a, arguments[b]);
			return a
		},

		//创建一个类,如果name为一个string类型的名称,则类定义在Ymt上，否则是创建一个类，ext是静态方法，inc是原型方法。
		create: function (name, ext, inc) {
			var Class = function () {
					if (!(this instanceof Class)) {
						return new Class(arguments);
					}
					if (typeof this.init == "function") {
						return this.init.apply(this, arguments[0]);
					}
				},
				bool = $m.isString(name);
			if (!bool) {
				inc = ext;
				ext = name;
			}
			$m.isPlainObject(ext) && mix(Class, ext)
			$m.isPlainObject(inc) && mix(Class.prototype, inc);
			return bool ? (this[name] = Class) : Class;
		},

		//代理
		proxy: function (func) {
			var that = this;
			return (function () {
				return func.apply(that, arguments);
			});
		},

		//命名空间
		namespace: function () {
			var args = arguments,
				length = args.length,
				context = null,
				name,
				index,
				iLen,
				isGlobal = args[length - 1] === !0 && length--;
			for (var c = 0; c < length; ++c) {
				name = args[c].split(".");
				context = isGlobal ? window : $m;

				//"$m.widget.check"
				index = window[name[0]] === context ? 1 : 0;

				for (iLen = name.length; index < iLen; ++index) context = context[name[index]] = context[name[index]] || {}
			}
			return context
		},

		//延迟函数
		later: function (method, time, isInterval, context, args) {
			time = time || 0;
			context = context || {};
			var v = $m.makeArray(args),
				timeHandle;
			$m.isString(method) && (method = context[method]);

			j = function () {
				method.apply(context, v)
			};

			timeHandle = isInterval ? setInterval(j, time) : setTimeout(j, time);

			return {
				id: timeHandle,
				interval: isInterval,
				cancel: function () {
					this.interval ? clearInterval(timeHandle) : clearTimeout(timeHandle)
				}
			}
		},

		//$m.ready(fn)
		ready: function (fn) {
			if (!__deferred) {
				__deferred = $m.deferred();
			}
			if (fn) {
				__deferred.success(fn);
			}
			if (!isReady) {
				ready();
			}
			return this;
		}

	});
})(window, "Ymt");

//Ymt object type judge
(function (window, $m, undefined) {
	var toString = Object.prototype.toString,
		indexOf = Array.prototype.indexOf,
		trim = String.prototype.trim,
		p = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;

	$m.mix($m, {
		isUndefined: function (val) {
			return val === undefined
		},
		isBoolean: function (val) {
			return toString.call(val) === "[object Boolean]"
		},
		isString: function (val) {
			return toString.call(val) === "[object String]"
		},
		isNumber: function (val) {
			return toString.call(val) === "[object Number]" && isFinite(val)
		},
		isArray: function (val) {
			return toString.call(val) === "[object Array]"
		},
		isNodeList: function (val) {
			return toString.call(val) === "[object NodeList]"
		},
		isFunction: function (val) {
			return toString.call(val) === "[object Function]"
		},
		isPlainObject: function (val) {
			return val && toString.call(val) === "[object Object]" && !val.nodeType && !val.setInterval
		},
		isEmptyObject: function (val) {
			for (var c in val) return !1;
			return !0
		},
		isRegExp: function (val) {
			return toString.call(val) === "[object RegExp]";
		},
		each: function (obj, fun, context) {
			if (!obj) {
				return;
			}
			var length = obj.length,
				isPlainObjectOrFun = length === undefined || $m.isFunction(obj);

			context = context || window;
			if (isPlainObjectOrFun) {
				for (var g in obj) {
					if (fun.call(context, obj[g], g, obj) === !1) break;
				}
			} else {
				for (var index = 0; index < length; index++) {
					if (fun.call(context, obj[index], index, obj) === !1) break;
				}
			}
			return obj
		},
		trim: trim ? function (val) {
			return val == undefined ? "" : trim.call(val)
		} : function (val) {
			return val == undefined ? "" : val.toString().replace(p, "")
		},
		indexOf: indexOf ? function (item, arr) {
			return indexOf.call(arr, item)
		} : function (item, arr) {
			for (var h = 0, g = arr.length; h < g; ++h)
				if (arr[h] === item) return h;
			return -1
		},
		inArray: function (item, arr) {
			return $m.indexOf(item, arr) > -1
		},

		//把val变成数组
		makeArray: function (val) {
			if (val === null || val === undefined) return [];
			if ($m.isArray(val)) return val;
			if (!$m.isNumber(val.length) || $m.isString(val) || $m.isFunction(val)) return [val];
			return Array.prototype.slice.call(val)
		},
		getJSON: function (url, data, callback) {
			return $m.get(url, data, callback, "json");
		},
		parseURL: function (url) {
			var arr = /^(?:((?:http|https|ftp|news):)\/\/)?([^\/:]*)(?:\:(\d+))?([^\?]*)(\?[^?#]+)?(#.+)?/i.exec(url);

			var _search = arr[5];
			var _query, _queryObj = null;

			if (_search) {
				_query = _search.slice(1).split("&");
				$m.each(_query, function (keyval, index) {
					keyval = keyval.split("=");
					_queryObj = _queryObj || {};
					_queryObj[keyval[0]] = keyval[1];
				})
			}
			return {
				hash: arr[6] || '',
				pathname: arr[4],
				protocol: arr[1],
				hostname: arr[2],
				search: arr[5],
				port: arr[3],
				query: _queryObj
			}
		},
		parseHost: function (url) {
			var h = /^.*?\/\/(.*?)(?:\/|$)/i;
			return h.exec(url);
		},
		toJSON: function (data) {
			if (window.JSON && window.JSON.stringify) {
				return window.JSON.stringify(data);
			}
		},
		parseJSON: function (data) {
			if (data && window.JSON && window.JSON.parse) {
				return window.JSON.parse(data);
			} else {
				return (new Function("return " + data))();
			}
		},
		toParameter: function (obj, sp) {
			var i, str = [];

			function build(a, b) {
				b = typeof b === "function" ? b() : b == null || b == undefined ? "" : b;
				if (typeof b === "object") {
					$m.each(b, function (m, n) {
						build(a + "[" + n + "]", m);
					})
					return;
				}
				str.push(encodeURIComponent(a) + "=" + encodeURIComponent(b));
			}
			if ($m.isNodeList(obj)) {
				$m.each(obj, function (a, b) {
					build(a.name, a.value);
				});
				return;
			}
			if ($m.isArray(obj) || $m.isPlainObject(obj)) {
				$m.each(obj, function (a, b) {
					build(b, a);
				});
			}
			return ('?' + str.join(sp || "&")).replace(/%20/g, "+");
		}
	});
})(window, $m);
$m.create('data', {
    expando: "DATAEXPANDO" + parseInt(Math.random() * 10e5),
    cache: {},
    uuid: 1,
    get: function (obj, key) {
        if (!obj) {
            return null;
        }
        var id = obj[this.expando];
        if (!id) {
            return null;
        }
        if (!key) {
            return this.cache[id]
        }
        return this.cache[id][key];
    },
    set: function (obj, key, value) {
        if (obj != null && typeof key == "string" && value) {
            var id = obj[this.expando];
            obj[this.expando] = id = id ? id : this.uuid++;
            this.cache[id] = this.cache[id] || {};
            this.cache[id][key] = value;
            return value;
        }
    },
    del: function (obj, key) {
        if (!obj) {
            this.cache = null;
        }
        var id = obj[this.expando];
        if (!id) {
            return;
        }
        if (!key) {
            obj[this.expando] = null;
            delete this.cache[id]
        }
        delete this.cache[id][key];
    }
}, null);
//deferred
$m.create('deferred', {
    when: function (param) {
        var args = $m.makeArray(arguments),
            length = args.length,
            count = length !== 1 || (param && $m.isFunction(param.promise)) ? length : 0,
            deferred = count == 1 ? param : $m.deferred(),
            parameters = [],
            contexts = [],
            update = function (i, type) {
                return function (value) {
                    contexts[i] = this;
                    parameters[i] = value;
                    if (type == "notify") {
                        deferred.notify();
                        return;
                    }
                    if (!--count) {
                        deferred.resolve.apply(contexts, parameters);
                    }
                }
            };
        if (length > 1) {
            for (var i = 0; i < length; i++) {
                (function (i) {
                    var item = args[i];
                    if (item && $m.isFunction(item.promise)) {
                        item.promise().success(update(i, "resolve")).fail(deferred.reject).progress(update(i, "notify"));
                    } else {
                        --count;
                    }
                })(i)
            }
        }
        if (!count) {
            deferred.resolve();
        }
        return deferred.promise();
    }
}, {
    init: function (fun) {
        var scene = ['resolve.success', 'reject.fail', 'notify.progress'],
            state = "pending",
            promise = {
                state: function () {
                    return state;
                },
                then: function (success, fail, progress) {
                    var fns = arguments;
                    return $m.deferred(function (defer) {
                        $m.each(scene, function (m, n) {
                            m = m.split('.');
                            var fn = $m.isFunction(fns[n]) && fns[n];
                            that[m[1]](function () {
                                var ret = fn && fn();
                                if (ret && typeof ret.promise == "function") {
                                    ret.promise().success(defer.resolve).fail(defer.reject).progress(defer.notify)
                                } else {
                                    defer[m[0]]();
                                }
                            });
                        })
                        fns = null;
                    }).promise();
                },
                always: function () {
                    that.success(arguments).fail(arguments);
                    return mise;
                },
                promise: function (obj) {
                    return obj != null ? $m.mix(obj, promise) : promise;
                }
            },
            that = this,
            obs = $m.event();
        $m.each(scene, function (m, n) {
            m = m.split('.');
            that[m[0]] = function () {
                var args = $m.makeArray(arguments), context = this === that ? promise : this;
                args.unshift(m[1]);
                obs.emit.apply(obs, args);
                state = m[1];
                return this
            }
            promise[m[1]] = function (fn) {
                obs.on(m[1], fn);
                return this
            };
        });
        that['off'] = function (type) {
            obs.off(type)
        }
        promise.promise(that);
        if (fun) {
            fun.call(that, that);
        }
    }
});
//cmd module 
(function (window, $m, l) {

    var ___VERSION = '';

    function getBasePath() {
        var result = "",
            reg = /ymt\.*([\d]*)?\.js(\W|$)/i,
            _statck;
        try {
            ab.bc();
        }
        catch (e) {

            //ff,safari,opera,chrome
            result = e.fileName || e.sourceURL || e.stacktrace && (_statck = e.stacktrace.match(/\(\) in\s+(.*?\:\/\/\S+)/m), _statck && _statck[1]) || e.stack && (_statck = e.stack.match(/\(([^)]+)\)/), _statck && _statck[1])

        }
        if (!result) {
            //IE与chrome4- opera10+
            var scripts = document.getElementsByTagName("script");
            var src;
            for (var i = 0, el; el = scripts[i++];) {
                src = !!document.querySelector ? el.src :
                    el.getAttribute('src', 4);

                if (src && reg.test(src)) {
                    result = src;
                    break;
                }
            }
        }
        var ret = reg.exec(result);
        ___VERSION = ret[1] || '';
        return result.substr(0, result.lastIndexOf('/'));
    }

    var doc = window.document,
        head = doc.getElementsByTagName("head")[0],
        requireReg = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
        commentReg = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*))$/mg,
        suffixType = /\.(js|css|jpg|png|gif|bmp|tiff|jpeg)(?:\?|$)/i,
        loadState = /^(?:loaded|complete|undefined)$/,
        addingScript = null,
        activeScript = null,
        isIE = !!doc.attachEvent,
        __anonymousData = null,
        __mainJsPath = getBasePath(),
        //核心框架所在的目录名，也是所有资源的root目录
        __idleading = __mainJsPath.slice(__mainJsPath.lastIndexOf("/") + 1),
        __basePath = $m.parseHost(__mainJsPath)[0],
        getCurrentScript = function () {
            if (addingScript) {
                return addingScript;
            }
            if (activeScript && activeScript.readyState === "interactive") {
                return activeScript;
            }
            var ss = head.getElementsByTagName("script"),
                s;
            for (var i = ss.length - 1; i >= 0; i--) {
                s = ss[i]
                if (s.readyState === "interactive") {
                    activeScript = s
                    return activeScript
                }
            }
        },
        //加载模块
        onload = function (id, success, error, charset) {
            var type = suffixType.exec(id),
                path = fullPath(id),
                elem, timeout, config = require.config;
            addingScript = elem;
            if (type && type[1] === 'css') {
                elem = doc.createElement("link");
                elem.rel = "stylesheet";
                elem.type = "text/css";
                elem.href = path;
                head.appendChild(elem)
            }
            else {
                elem = doc.createElement("script");
                elem.charset = charset || config.charset;
                elem.src = path;
                elem.async = config.async;
                addingScript = elem;
                head.insertBefore(elem, head.firstChild)
            }
            error = error || config.error;
            var A = elem.readyState ? function (a, b) {
                var e = a.onreadystatechange;
                a.onreadystatechange = function () {
                    if (loadState.test(a.readyState)) {
                        this.onreadystatechange = null;
                        b.call(this, id);
                    }
                }
            } : function (a, b) {
                a.addEventListener("load", b, !1);
            };

            A(elem, function () {
                timeout && timeout.cancel();
                success && success.call(elem);
            });

            timeout = $m.later(function () {
                timeout.cancel();
                error.call($m, id)
            }, config.timeout);

            addingScript = null;
        },
        //定义模块
        define = function (id, deps, fn) {
            if (typeof id !== "string") {
                fn = deps;
                deps = id;
                id = null;
            }
            if (!$m.isArray(deps)) {
                fn = deps;
                deps = null;
            }
            if (!deps && $m.isFunction(fn)) {
                deps = [];
                fn.toString().replace(commentReg, '').replace(requireReg, function (m, n) {
                    var type = suffixType.exec(n);
                    if (type && type[1] != 'js') {
                        onload(n);
                    }
                    else {
                        deps.push(n);
                    }
                    return m;
                });
            }
            var length = deps.length,
                i = 0;
            if (id && length) {
                //把__idleading加入模块id中
                for (i; i < length; i++) {
                    deps[i] = deps[i].replace(/\\/g, '\/');
                    deps[i] = fullId(deps[i], id);
                }
            }

            //取合成脚本第一个模块
            __anonymousData = __anonymousData || {
                id: id,
                dependencies: deps,
                factory: fn
            };

            if (!id && isIE) {
                var s = getCurrentScript();
                if (s) {
                    id = s.src.replace(__basePath, '').replace(/(?:\.\d+)*\.js/i, '');
                }
            }
            if (id) {
                Module.done(id, deps, fn)
            }
        },
        //换算完整id
        fullId = function (id, path) {
            path = path || '';
            var str = id.charAt(0),
                index = path.lastIndexOf('/');
            if (index > 0) {
                path = path.slice(0, index + 1);
            }
            if (str == '/') {
                id = path + __idleading + id;
            }
            else if (str == '.') {
                if (!path) {
                    path = __idleading + '/';
                }
                id = path + id;
            }
            var dotreg = /\/[^\/]+\/\.\.\//;
            while (dotreg.test(id)) {
                id = id.replace(dotreg, "/")
            }
            id = id.replace(/\.\//g, "/").replace(/(?!=[^:])\/\//g, "/");
            return id;
        },
        //绝对地址
        fullPath = function (id) {
            if ($m.parseHost(id)) {
                return id;
            }
            id = addVersionAndSuffix(id);
            return __basePath + fullId(id);
        },
        //a.b to a/b
        dotToSprit = function (str) {
            return str.replace(/(?=[\w-])\.(?=[\w-])/g, '\/');
        },
        //id转换成dir
        idtodir = function (id, path) {
            id = dotToSprit(id);
            id = fullId(id, path);
            return id;
        },
        //给资源加版本号
        addVersionAndSuffix = function (uri) {
            var version = require.config.version ? "." + require.config.version : "";
            if (suffixType.test(uri)) {
                uri = uri.replace(suffixType, function (a, b) {
                    return version + a;
                })
            }
            else {
                uri += version + '.js';
            }
            return uri;
        },
        //命名空间句柄
        handle = function (a, f) {
            var b, e;
            a.indexOf("/") > 0 ? (b = a.split(/[\.\/]/), e = b[b.length - 1], b.length--, $m.namespace(b.join("."))[e] = f) : $m[a] = f;
        },
        require = function (id, fn) {
            var arr = $m.isArray(id) ? id : id.split(/[,]/),
                mod;
            $m.each(arr, function (a, b) {
                if (a.slice(0, 2) != "./") {
                    a = "./" + a;
                }
                arr[b] = $m.trim(a);
            });
            mod = Module.done("YMTMODULE" + Math.floor(Math.random() * 1e3), arr);
            mod.callback = function () {
                var deps = mod.dependencies,
                    len = deps.length,
                    i, exports = [];
                for (i = 0; i < len; i++) {
                    exports[i] = Module.done(deps[i]).execute()
                }
                if (typeof fn == "function") {
                    fn.apply(window, exports)
                }
                delete mod.callback;
            }
            mod.load()
        },
        Module = function (id, deps, factory) {
            this.id = id;
            this.fileName = null;
            if (id) {
                var index = id.lastIndexOf("/");
                this.fileName = index > -1 ? id.slice(index) : id;
            }
            this.dependencies = deps || [];
            this.exports = {};
            this.state = 0;
            this.factory = factory || null;
            this.count = 0;
            this.parent = null
        },
        STATE = {
            INIT: 1,
            FETCH: 2,
            LOAD: 3,
            EXECUT: 4
        };
    $m.augment(Module, {
        load: function () {
            if (!this.state) {
                this.state = STATE.INIT;
            }
            //父业子承
            var deps = this.dependencies,
                i, mod;
            this.count = deps.length;
            for (i = 0; i < deps.length; i++) {
                mod = Module.done(deps[i]);
                if (mod.factory || !$m.isEmptyObject(mod.exports)) {
                    deps.splice(i, 1);
                    mod.state = STATE.LOAD;
                    i--;
                }
                mod.parent = mod.parent || [];
                Module.inlist(this.id, mod.parent);
                if (mod.state < STATE.FETCH) {
                    mod.fetch();
                }
                if (mod.state >= STATE.LOAD) {
                    this.count--;
                }
            }
            if (this.count === 0) {
                this.resolve();
            }
        },
        fetch: function () {
            var mod = this,
                callback = function () {
                    if (__anonymousData) { //__anonymousData && !isIE
                        mod.dependencies = __anonymousData.dependencies;
                        mod.id = __anonymousData.id || mod.id;
                        mod.factory = __anonymousData.factory;
                        __anonymousData = null;
                    }

                    mod.state = STATE.LOAD;
                    mod.load();
                };
            //isIE && (__anonymousData = null);
            mod.state = STATE.FETCH;
            onload(mod.id, callback, require.config.error, require.config.charset)
        },
        resolve: function () {
            var mod = this;

            function d(mod) {
                mod.execute();
                if (mod.callback) {
                    mod.callback();
                }
                mod.parent && $m.each(mod.parent, function (a, b) {
                    var m = Module.done(a);
                    if (m.count > 0 && (--m.count === 0)) {
                        d(m);
                    }
                });
            }
            d(this);
        },
        execute: function (id) {
            if (this.state == STATE.EXECUT) {
                return this.exports;
            }
            this.state = STATE.EXECUT;
            var that = this;

            function require(id) {
                var type = suffixType.exec(id);
                if (!type || (type && type[1] === 'js')) {
                    return Module.done(id, null, null, that.id).execute();
                }
            }

            require.async = function (id, callback) {
                window.require(id, callback)
            }
            var exports = typeof this.factory == "function" ? this.factory.apply(window, [require, this.exports, this, $m]) : this.factory;

            if (exports) {
                this.exports = exports;
            }
            handle(this.id, this.exports)
            //this.factory = null;
            return this.exports;
        }
    });
    $m.mix(Module, {
        done: function (id, depend, fn, path) {
            id = idtodir(id, path);
            if (Module.mods[id]) {
                depend && (Module.mods[id].dependencies = depend);
                fn && (Module.mods[id].factory = fn);
                return Module.mods[id];
            }
            return (Module.mods[id] = new Module(id, depend, fn));
        },
        mods: {},
        modlist: [],
        inlist: function (id, array) {
            array = array || Module.modlist;
            return $m.inArray(id, array) || (array.push(id));
        }
    });
    require.config = {
        csspath: 'css/',
        charset: "utf-8",
        timeout: 10 * 1E3,
        async: !0,
        error: function (r) {
            $m.log(r + " load error");
        },
        base: __basePath,
        version: ___VERSION
    };

    $m.load = window.require = require;
    window.define = $m.add = window.define || define;
    $m.onload = onload;
})(window, $m);
(function (require) {
	var _host = /static\.ymatou\.com/ig;

	if (_host.test(require.config.base)) {
		//require.config.version = "2015060510";
		$m.isOnline = true;
	}
	else {
		//require.config.version = "";
		$m.isOnline = !1;
	}

})($m.load);
